<template>
  <div id="app" style="height: 100%">
    <router-view/>
  </div>
</template>

<script>
  import {getUserData, getWeChatConfigParams} from './api/api'

  export default {
    name: 'App',
    data() {
      return {
        code: '',
        user: null,
      }

    },
    watch:{
      "$route"(){
        if (/iPhone|mac|iPod|iPad/i.test(navigator.userAgent)) {
          let httpHost=window.location.protocol+'//'+window.location.host
          location.href = httpHost + this.$route.fullPath
        }
      },
    },
    mounted() {

    },
    created() {
      // alert(2222)
      // return ;
      this.code = this.getQueryString('code'); //从url上取到code

      if (this.code) {
        //code不为空
        localStorage.setItem('code', this.code);

        let url=this.dealCode(window.location.href);
        window.history.pushState({},0,url);
        // window.location.href=/
      } else { //从缓存取到code
        //code为空
        this.code = localStorage.getItem('code');

      }
      if (this.isInWeXin() && !this.code) { //从授权中取到code

        this.getCode();
      } else {

        getUserData({code: this.code, shopId: 'system'}).then((res) => {

          console.log(res.data);
          if (res.data.errcode) {
            this.state = '';
            console.log('error:' + res.data.errcode);
            localStorage.removeItem('code');
            this.getCode();


          } else {
            console.log('已更新user');
            sessionStorage.setItem("user", JSON.stringify(res.data));
            sessionStorage.setItem('openid', res.data.openid);

            this.$store.state.dataChanged = !this.$store.state.dataChanged;

          }


        }).catch((err) => {
          localStorage.removeItem('code');
        })
      }

    },
    methods: {
      isInWeXin: function () {
        var ua = navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == "micromessenger") {
          return true;
        } else {
          return false;
        }
      },

      getCode() {
        let redirect_uri = encodeURI(window.location.href);

        let scope = 'snsapi_userinfo';
        let appid = 'wxbfe1a3fb88d4eafe';
        let wxLogin = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid + '&redirect_uri=' + redirect_uri + '&response_type=code&scope=' + scope + '&state=STATE#wechat_redirect';

        window.location.href = wxLogin;
      }




    }


  }
</script>

<style>
  #app {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    color: #2c3e50;
  }
</style>
